using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace ZSW.Framework.EditorTools
{
    /// <summary>
    /// 找到场景中与预制体同名的物体，替换为预制体保留Transform
    /// 支持撤回
    /// </summary>
    public class ReplacePrefabByName : EditorWindow
    {
        private GameObject prefab;

        [MenuItem("Tools/Transform/Replace Prefab By Name")]
        public static void Invoke()
        {
            GetWindow(typeof(ReplacePrefabByName));
        }

        public void OnGUI()
        {
            prefab = (GameObject)EditorGUILayout.ObjectField("Prefab", prefab, typeof(GameObject), false);

            if (GUILayout.Button("Replace"))
            {
                if (prefab == null)
                {
                    Debug.LogError("Prefab is null");
                    return;
                }

                Replace();
            }
        }

        public void Replace()
        {
            GameObject[] allObjects = FindObjectsOfType<GameObject>(true);
            List<GameObject> objectsToReplace = new List<GameObject>();
            int count = 0;

            foreach (GameObject go in allObjects)
            {
                if (go.name == prefab.name)
                {
                    objectsToReplace.Add(go);
                }
            }

            foreach (GameObject go in objectsToReplace)
            {
                GameObject newObject = (GameObject)PrefabUtility.InstantiatePrefab(prefab);
                if (newObject == null)
                {
                    Debug.LogError("Could not instantiate prefab");
                    continue;
                }
                count++;

                Undo.RegisterCreatedObjectUndo(newObject, "Replace With Prefabs");
                newObject.transform.position = go.transform.position;
                newObject.transform.rotation = go.transform.rotation;
                newObject.transform.localScale = go.transform.localScale;
                newObject.transform.parent = go.transform.parent;
                newObject.name = $"{go.name} ({count})";

                Undo.DestroyObjectImmediate(go);
            }
        }
    }
}